from flask import Flask, jsonify, request
# 自动化使用python发送邮件
import smtplib
from email.mime.text import MIMEText
from email.header import Header

app = Flask(__name__)
@app.route('/data', methods=['GET'])
def get_data():
    subject = "python邮件发送功能测试完成!!!!!"  # 项目标题
    content = "使用Python发送邮件测试案例，接收是否能收到邮件"

    snedStatus = send_qq_mail(subject, content)
    # 这里只是示例，实际中你可能需要从数据库或其他数据源获取数据
    data = {'message': snedStatus}
    return jsonify(data)

@app.route('/send_email', methods=['POST'])
def submit_form():
    if request.method == 'POST':
        data = request.form
        required_fields = ['subject', 'content', 'receiver']
        missing_fields = [field for field in required_fields if field not in data]

        if missing_fields:
          return jsonify({'error': '缺少上传的字段', '缺少上传的字段': missing_fields}), 400
        snedStatus = send_qq_mail(
            data['subject'], data['content'], data['receiver'])
        data = {'message': snedStatus, 'data': data}
        return jsonify(data), 200
    else:
        return 'Method not allowed!'

@app.route('/post_endpoint', methods=['POST'])
def handle_post_request():
    # 从请求中获取JSON数据
    data = request.form
    # 打印接收到的数据（可选，用于调试）
    print(data)
    return jsonify(data), 200


def send_qq_mail(subject, content, receiver):
    sender = "573561243@qq.com"
    smtpserver = "smtp.qq.com"
    port = 465
    user = '573561243@qq.com'
    password = 'breaqfwfnvtxbfgf'  # 请确保这是正确的密码或授权码

    msg = MIMEText(content, 'plain', 'utf-8')  # 发送的文本信息
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = sender  # 应该使用 sender 变量，而不是 user（尽管在这里它们是相同的）
    msg['To'] = receiver
    try:
        # smtp = smtplib.SMTP()
        # 在实例化时传入服务器地址和端口号
        smtp = smtplib.SMTP_SSL(smtpserver, port)
        smtp.login(user, password)
        # 注意 receiver 应该是一个列表
        smtp.sendmail(sender, [receiver], msg.as_string())
        smtp.quit()  # 显式关闭连接是一个好习惯
        return ("邮件发送成功！！！")
    except smtplib.SMTPException:
        print("Error: 无法发送邮件")
        return ("Error: 无法发送邮件")

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5050, debug=True)
